# -*- coding: utf-8 -*-
from urllib import parse
import base64
import hashlib
import time
import requests
import urllib3
from urllib3.util.retry  import Retry 
from urllib3.util.timeout  import Timeout 
from urllib3.util.url  import parse_url 
"""
  手写文字识别WebAPI接口调用示例接口文档(必看):https://doc.xfyun.cn/rest_api/%E6%89%8B%E5%86%99%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB.html
  图片属性：jpg/png/bmp,最短边至少15px，最长边最大4096px,编码后大小不超过4M,识别文字语种：中英文
  webapi OCR服务参考帖子(必看)：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=39111&highlight=OCR
  (Very Important)创建完webapi应用添加服务之后一定要设置ip白名单，找到控制台--我的应用--设置ip白名单，如何设置参考：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=41891
  错误码链接：https://www.xfyun.cn/document/error-code (code返回错误码时必看)
  @author iflytek
"""
# OCR手写文字识别接口地址
URL = "https://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
       
# 应用APPID(必须为webapi类型应用,并开通手写文字识别服务,参考帖子如何创建一个webapi应用：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
APPID = "26dfc7ce"
# 接口密钥(webapi类型应用开通手写文字识别后，控制台--我的应用---手写文字识别---相应服务的apikey)
API_KEY = "d68e26e9f1bc23f2edf934d9a25b8dce"
def getHeader():
    curTime = str(int(time.time()))
    param = "{\"language\":\""+language+"\",\"location\":\""+location+"\"}"
    paramBase64 = base64.b64encode(param.encode('utf-8'))

    m2 = hashlib.md5()
    str1 = API_KEY + curTime + str(paramBase64, 'utf-8')
    m2.update(str1.encode('utf-8'))
    checkSum = m2.hexdigest()
	# 组装http请求头
    header = {
        'X-CurTime': curTime,
        'X-Param': paramBase64,
        'X-Appid': APPID,
        'X-CheckSum': checkSum,
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    }
    return header
def getBody(filepath):
    with open(filepath, 'rb') as f:
        imgfile = f.read()
    data = {'image': str(base64.b64encode(imgfile), 'utf-8')}
    return data

def process_image(image_path):
    # 将原有执行代码封装成函数
    try:
        response = requests.post(URL, headers=getHeader(), data=getBody(image_path), verify=False)
        if response.status_code == 200:
            return response.json()['data']['ocr']['content']
        return f"OCR Error: {response.text}"
    except Exception as e:
        return f"OCR Exception: {str(e)}"

# 需要移除最后的直接执行代码（重要！）
if __name__ == "__main__":
    # 以下代码仅在本文件直接运行时执行
    r = requests.post(URL, headers=getHeader(), data=getBody(picFilePath))
    print(r.content)
    
    try:
        r = requests.post(URL, headers=getHeader(), data=getBody(picFilePath), verify=False)
        print(r.content)
    except Exception as e:
        print(f"请求失败: {str(e)}")

# 语种设置
language = "en"
# 是否返回文本位置信息
location = "true"
# 图片上传接口地址
picFilePath = "D:\AiPro\english\ocr_handwriting_python3_demo\ocr_handwriting_python3.x_demo\ocr.jpg"
# headers=getHeader(language, location)
# 配置SSL参数（新增以下三行）
# ctx = urllib3.util.ssl_.create_urllib3_context()
# ctx.set_ciphers('DEFAULT:!DH')
# urllib3.contrib.pyopenssl.inject_into_ur


